package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Menu;

import com.itheima.dao.MenuDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Menu;
import com.itheima.pojo.SysUser;

import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;


@Service
public class MenuServiceImpl implements MenuService {


    @Autowired
    MenuDao menuDao;

    @Autowired
    UserDao userDao;

    @Override
    public void add(Menu menu) {
        Integer parentMenuId = menu.getParentMenuId();
        if (parentMenuId != null) {
            menu.setLevel(1);
        } else {
            menu.setLevel(2);
        }
        menuDao.add(menu);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //1. 开始分页
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //2. 根据条件查询（返回值：Page）
        Page<Menu> page = menuDao.findByCondition(queryPageBean.getQueryString());
        //创建返回值
        PageResult pageResult = new PageResult(page.getTotal(), page);
        return pageResult;
    }

    @Override
    public void delById(Integer id) {
        menuDao.delById(id);
    }

    @Override
    public Menu findById(Integer id) {
        return menuDao.findById(id);
    }

    @Override
    public void edit(Menu menu) {
        Integer parentMenuId = menu.getParentMenuId();
        if (parentMenuId != null) {
            menu.setLevel(1);
        } else {
            menu.setLevel(2);
        }
        menuDao.edit(menu);
    }

    @Override
    public List<Menu> findFu() {
        return menuDao.findFu();
    }


    @Override
    public List<Menu> findMenuByUserId(String username) {
        SysUser byUsername = userDao.findByUsername(username);
        List<Menu> parent = menuDao.findMenuParent(byUsername.getId());
        parent.forEach(menu -> {
            List<Menu> child = menuDao.findChiledById(byUsername.getId(), menu.getId());
            menu.setChildren(child);
        });

        return parent;
    }

    @Override
    public List<Menu> findAll() {
        return menuDao.findAll();
    }

    @Override
    public List<Integer> findByRoleId(Integer id) {
        return menuDao.findByRoleId(id);
    }
}

